package cn.lj.controller;

import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.StrUtil;
import cn.lj.entity.Role;
import cn.lj.entity.User;
import cn.lj.entity.UserRole;
import cn.lj.response.Const;
import cn.lj.response.Result;
import cn.lj.service.RoleService;
import cn.lj.service.UserRoleService;
import cn.lj.service.UserService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.security.Principal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author 李津
 * @since 2021-05-19
 */
@RestController
@RequestMapping("/sys/user")
@Api(value = "系统用户模块",tags = "系统用户接口")
public class UserController {
    //构造器注入
    private final UserService userService;

    private final BCryptPasswordEncoder passwordEncoder;

    private final RoleService roleService;

    private final UserRoleService userRoleService;

    @Autowired
    public UserController(UserService userService, BCryptPasswordEncoder passwordEncoder, RoleService roleService, UserRoleService userRoleService) {
        this.userService = userService;
        this.passwordEncoder = passwordEncoder;
        this.roleService = roleService;
        this.userRoleService = userRoleService;
    }

    /**
     * 查询用户信息
     * @return
     */
    @GetMapping("/info/{id}")
    @PreAuthorize("hasAuthority('sys:user:list')")
    @ApiOperation(value = "单个用户",notes = "查询单个用户")
    public Result findUserById(@PathVariable Long id){
        User user = userService.getById(id);
        Assert.notNull(user,"找不到该管理员！");
        user.setPassword("");

        List<Role> roles = roleService.listRolesByUserId(id);
        user.setRoles(roles);

        return Result.ok().data(user);
    }


    /**
     * 查询所有用户信息
     * @return
     */
    @GetMapping("/list")
    @PreAuthorize("hasAuthority('sys:user:list')")
    @ApiOperation(value = "用户列表",notes = "查询所有用户信息")
    public Result findUsers(@RequestParam(defaultValue = "1")Integer current, @RequestParam(defaultValue = "8")Integer size
            , String username){
        Page<User> page = new Page<>(current,size);
        Page<User> pageData = userService.page(page,
                new QueryWrapper<User>()
                        .like(StrUtil.isNotBlank(username), "username", username)
        );
        pageData.getRecords().forEach(u -> u.setRoles(roleService.listRolesByUserId(u.getId())));

        return Result.ok().data(pageData);
    }

    /**
     * 新增用户
     * @param user
     * @return
     */
    @PostMapping("/save")
    @PreAuthorize("hasAuthority('sys:user:save')")
    @ApiOperation(value = "新增用户",notes = "新增用户")
    public Result saveUser(@Validated @RequestBody User user){
        user.setCreated(LocalDateTime.now());
        // 默认头像
        user.setAvatar(Const.DEFULT_AVATAR);

        user.setPassword(passwordEncoder.encode(user.getPassword()));
        userService.save(user);
        return Result.ok();
    }

    /**
     * 修改用户
     * @param user
     * @return
     */
    @PostMapping("/update")
    @PreAuthorize("hasAuthority('sys:user:update')")
    @ApiOperation(value = "修改用户",notes = "修改用户")
    public Result updateUser(@Validated @RequestBody User user){
        user.setUpdated(LocalDateTime.now());

        user.setPassword(passwordEncoder.encode(user.getPassword()));
        userService.updateById(user);
        return Result.ok();
    }

    /**
     * 删除用户
     * @param ids
     * @return
     */
    @Transactional
    @PostMapping("/delete")
    @PreAuthorize("hasAuthority('sys:user:delete')")
    @ApiOperation(value = "删除用户",notes = "删除用户")
    public Result deleteUser(@RequestBody Long[] ids){
        userService.removeByIds(Arrays.asList(ids));

        userRoleService.remove(new QueryWrapper<UserRole>().in("user_id", (Object) ids));
        return Result.ok();
    }


    /**
     * 改变用户的角色
     * @param userId
     * @param roleIds
     * @return
     */
    @Transactional
    @PostMapping("/role/{userId}")
    @PreAuthorize("hasAuthority('sys:user:role')")
    @ApiOperation(value = "改变用户的角色",notes = "改变用户的角色")
    public Result rolePerm(@PathVariable("userId") Long userId, @RequestBody Long[] roleIds) {
        List<UserRole> userRoles = new ArrayList<>();

        //增加角色
        Arrays.stream(roleIds).forEach(r -> {
            UserRole sysUserRole = new UserRole();
            sysUserRole.setRoleId(r);
            sysUserRole.setUserId(userId);
            userRoles.add(sysUserRole);
        });

        //删除角色
        userRoleService.remove(new QueryWrapper<UserRole>().eq("user_id", userId));
        userRoleService.saveBatch(userRoles);

        // 删除缓存
        User sysUser = userService.getById(userId);
        userService.clearUserAuthorityInfo(sysUser.getUsername());

        return Result.ok().data(roleIds);
    }


    /**
     * 重置密码
     * @param userId
     * @return
     */
    @PostMapping("/repass")
    @PreAuthorize("hasAuthority('sys:user:repass')")
    @ApiOperation(value = "重置密码",notes = "重置密码")
    public Result repass(@RequestBody Long userId) {

        User sysUser = userService.getById(userId);

        sysUser.setPassword(passwordEncoder.encode(Const.DEFULT_PASSWORD));
        sysUser.setUpdated(LocalDateTime.now());

        userService.updateById(sysUser);
        return Result.ok();
    }

    /**
     * 获取用户信息接口
     * @param principal
     * @return
     */
    @GetMapping("/userInfo")
    @ApiOperation(value = "系统获取用户信息",notes = "获取用户信息接口")
    public Result userInfo(Principal principal) {

        User sysUser = userService.getByUserName(principal.getName());

        Map<Object, Object> userInfo = MapUtil.builder()
                .put("id", sysUser.getId())
                .put("username", sysUser.getUsername())
                .put("avatar", sysUser.getAvatar())
                .put("created", sysUser.getCreated())
                .map();

        return Result.ok().data(userInfo);
    }
}

